Clustering and Classification

date()
## [1] "Thu Nov 24 22:09:25 2022"

Read the data

library(MASS)

# load the data
data("Boston")

# explore the dataset
str(Boston)
## 'data.frame':    506 obs. of  14 variables:
##  $ crim   : num  0.00632 0.02731 0.02729 0.03237 0.06905 ...
##  $ zn     : num  18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
##  $ indus  : num  2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
##  $ chas   : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ nox    : num  0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
##  $ rm     : num  6.58 6.42 7.18 7 7.15 ...
##  $ age    : num  65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
##  $ dis    : num  4.09 4.97 4.97 6.06 6.06 ...
##  $ rad    : int  1 2 2 3 3 3 5 5 5 5 ...
##  $ tax    : num  296 242 242 222 222 222 311 311 311 311 ...
##  $ ptratio: num  15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
##  $ black  : num  397 397 393 395 397 ...
##  $ lstat  : num  4.98 9.14 4.03 2.94 5.33 ...
##  $ medv   : num  24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...
dim(Boston)
## [1] 506  14
View(Boston)

This data consists of housing values in Suburbs of Boston. It has 506 observations and 14 variables. The variables are as follows : crim (per capita crime rate by town), zn (proportion of residential land zoned for lots over 25,000 sq.ft.), indus (proportion of non-retail business acres per town.), chas (Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)), nox (nitrogen oxides concentration (parts per 10 million)), rm (average number of rooms per dwelling.), age (proportion of owner-occupied units built prior to 1940), dis (weighted mean of distances to five Boston employment centres), rad (index of accessibility to radial highways), tax (full-value property-tax rate per $10,000), ptratio (pupil-teacher ratio by town), black (1000(Bk - 0.63)^21000(Bk−0.63) where BkBk is the proportion of blacks by town, lstat (lower status of the population (percent)), medv(median value of owner-occupied homes in $1000s).

None of the variables are categorical. All of them are numerical or integers.

Graphical overview and summaries of the variables

#Summary of the variable

summary(Boston)
##       crim                zn             indus            chas        
##  Min.   : 0.00632   Min.   :  0.00   Min.   : 0.46   Min.   :0.00000  
##  1st Qu.: 0.08205   1st Qu.:  0.00   1st Qu.: 5.19   1st Qu.:0.00000  
##  Median : 0.25651   Median :  0.00   Median : 9.69   Median :0.00000  
##  Mean   : 3.61352   Mean   : 11.36   Mean   :11.14   Mean   :0.06917  
##  3rd Qu.: 3.67708   3rd Qu.: 12.50   3rd Qu.:18.10   3rd Qu.:0.00000  
##  Max.   :88.97620   Max.   :100.00   Max.   :27.74   Max.   :1.00000  
##       nox               rm             age              dis        
##  Min.   :0.3850   Min.   :3.561   Min.   :  2.90   Min.   : 1.130  
##  1st Qu.:0.4490   1st Qu.:5.886   1st Qu.: 45.02   1st Qu.: 2.100  
##  Median :0.5380   Median :6.208   Median : 77.50   Median : 3.207  
##  Mean   :0.5547   Mean   :6.285   Mean   : 68.57   Mean   : 3.795  
##  3rd Qu.:0.6240   3rd Qu.:6.623   3rd Qu.: 94.08   3rd Qu.: 5.188  
##  Max.   :0.8710   Max.   :8.780   Max.   :100.00   Max.   :12.127  
##       rad              tax           ptratio          black       
##  Min.   : 1.000   Min.   :187.0   Min.   :12.60   Min.   :  0.32  
##  1st Qu.: 4.000   1st Qu.:279.0   1st Qu.:17.40   1st Qu.:375.38  
##  Median : 5.000   Median :330.0   Median :19.05   Median :391.44  
##  Mean   : 9.549   Mean   :408.2   Mean   :18.46   Mean   :356.67  
##  3rd Qu.:24.000   3rd Qu.:666.0   3rd Qu.:20.20   3rd Qu.:396.23  
##  Max.   :24.000   Max.   :711.0   Max.   :22.00   Max.   :396.90  
##      lstat            medv      
##  Min.   : 1.73   Min.   : 5.00  
##  1st Qu.: 6.95   1st Qu.:17.02  
##  Median :11.36   Median :21.20  
##  Mean   :12.65   Mean   :22.53  
##  3rd Qu.:16.95   3rd Qu.:25.00  
##  Max.   :37.97   Max.   :50.00

The Chas is a binary variable and the variable rad is an index variable. Some variables have a higher variability compared to some others. For example, the variable tax (full-value property-tax) ranges from 187 to 711 and the variable black (proportion of blacks by town) ranges from 0.32 to 396.90. However, the variable nox (nitrogen oxides concentration) ranges only from 0.3850 to 0.8710 and the variable rm (average number of rooms per dwelling) ranges only from 3.561 to 8.780.

# Graphical exploration of data

pairs(Boston)

Even though, this graph is somewhat complicated at first, we can get a rough idea about how the variables are. The correlation plot can be used for further understanding about the data.

library(tidyr)
library(corrplot)
## corrplot 0.92 loaded
# correlation matrix
cor_matrix <- cor(Boston)
cor_matrix %>% round(digits = 2)
##          crim    zn indus  chas   nox    rm   age   dis   rad   tax ptratio
## crim     1.00 -0.20  0.41 -0.06  0.42 -0.22  0.35 -0.38  0.63  0.58    0.29
## zn      -0.20  1.00 -0.53 -0.04 -0.52  0.31 -0.57  0.66 -0.31 -0.31   -0.39
## indus    0.41 -0.53  1.00  0.06  0.76 -0.39  0.64 -0.71  0.60  0.72    0.38
## chas    -0.06 -0.04  0.06  1.00  0.09  0.09  0.09 -0.10 -0.01 -0.04   -0.12
## nox      0.42 -0.52  0.76  0.09  1.00 -0.30  0.73 -0.77  0.61  0.67    0.19
## rm      -0.22  0.31 -0.39  0.09 -0.30  1.00 -0.24  0.21 -0.21 -0.29   -0.36
## age      0.35 -0.57  0.64  0.09  0.73 -0.24  1.00 -0.75  0.46  0.51    0.26
## dis     -0.38  0.66 -0.71 -0.10 -0.77  0.21 -0.75  1.00 -0.49 -0.53   -0.23
## rad      0.63 -0.31  0.60 -0.01  0.61 -0.21  0.46 -0.49  1.00  0.91    0.46
## tax      0.58 -0.31  0.72 -0.04  0.67 -0.29  0.51 -0.53  0.91  1.00    0.46
## ptratio  0.29 -0.39  0.38 -0.12  0.19 -0.36  0.26 -0.23  0.46  0.46    1.00
## black   -0.39  0.18 -0.36  0.05 -0.38  0.13 -0.27  0.29 -0.44 -0.44   -0.18
## lstat    0.46 -0.41  0.60 -0.05  0.59 -0.61  0.60 -0.50  0.49  0.54    0.37
## medv    -0.39  0.36 -0.48  0.18 -0.43  0.70 -0.38  0.25 -0.38 -0.47   -0.51
##         black lstat  medv
## crim    -0.39  0.46 -0.39
## zn       0.18 -0.41  0.36
## indus   -0.36  0.60 -0.48
## chas     0.05 -0.05  0.18
## nox     -0.38  0.59 -0.43
## rm       0.13 -0.61  0.70
## age     -0.27  0.60 -0.38
## dis      0.29 -0.50  0.25
## rad     -0.44  0.49 -0.38
## tax     -0.44  0.54 -0.47
## ptratio -0.18  0.37 -0.51
## black    1.00 -0.37  0.33
## lstat   -0.37  1.00 -0.74
## medv     0.33 -0.74  1.00
# visualize the correlation matrix
corrplot(cor_matrix, method="square", type="upper", cl.pos = "b", tl.pos = "d", col = COL2('PiYG'), addCoef.col = 'black', tl.cex = 0.6)

The bigger and more colourful the square in the cell is, the stronger the correlation is between the variables. The purple colour of the square indicates negative correlation while the green colour indicates a positive correlation. The highest positive correlation is between the variables: tax (full-value property-tax rate per $10,000) and rad (index of accessibility to radial highways).There is a 0.91 correlation between those two variables. The strongest negative correlation is between the varioables: nox (nitrogen oxides concentration (parts per 10 million)) and dis (weighted mean of distances to five Boston employment centres). There is a -0.77 correlation between those two variables. There is a 0.91 correlation between those two variables.

Standardize the dataset

# center and standardize variables
boston_scaled <- scale(Boston)

# summaries of the scaled variables
summary(boston_scaled)
##       crim                 zn               indus              chas        
##  Min.   :-0.419367   Min.   :-0.48724   Min.   :-1.5563   Min.   :-0.2723  
##  1st Qu.:-0.410563   1st Qu.:-0.48724   1st Qu.:-0.8668   1st Qu.:-0.2723  
##  Median :-0.390280   Median :-0.48724   Median :-0.2109   Median :-0.2723  
##  Mean   : 0.000000   Mean   : 0.00000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.007389   3rd Qu.: 0.04872   3rd Qu.: 1.0150   3rd Qu.:-0.2723  
##  Max.   : 9.924110   Max.   : 3.80047   Max.   : 2.4202   Max.   : 3.6648  
##       nox                rm               age               dis         
##  Min.   :-1.4644   Min.   :-3.8764   Min.   :-2.3331   Min.   :-1.2658  
##  1st Qu.:-0.9121   1st Qu.:-0.5681   1st Qu.:-0.8366   1st Qu.:-0.8049  
##  Median :-0.1441   Median :-0.1084   Median : 0.3171   Median :-0.2790  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.5981   3rd Qu.: 0.4823   3rd Qu.: 0.9059   3rd Qu.: 0.6617  
##  Max.   : 2.7296   Max.   : 3.5515   Max.   : 1.1164   Max.   : 3.9566  
##       rad               tax             ptratio            black        
##  Min.   :-0.9819   Min.   :-1.3127   Min.   :-2.7047   Min.   :-3.9033  
##  1st Qu.:-0.6373   1st Qu.:-0.7668   1st Qu.:-0.4876   1st Qu.: 0.2049  
##  Median :-0.5225   Median :-0.4642   Median : 0.2746   Median : 0.3808  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 1.6596   3rd Qu.: 1.5294   3rd Qu.: 0.8058   3rd Qu.: 0.4332  
##  Max.   : 1.6596   Max.   : 1.7964   Max.   : 1.6372   Max.   : 0.4406  
##      lstat              medv        
##  Min.   :-1.5296   Min.   :-1.9063  
##  1st Qu.:-0.7986   1st Qu.:-0.5989  
##  Median :-0.1811   Median :-0.1449  
##  Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.6024   3rd Qu.: 0.2683  
##  Max.   : 3.5453   Max.   : 2.9865
# class of the boston_scaled object
class(boston_scaled)
## [1] "matrix" "array"
# change the object to data frame
boston_scaled <- as.data.frame(scale(Boston))

Each and every mean of the summary of the scaled dataset is zero. It shows that after the standardization, all variables fit to a normal distribution.

# Create a categorical variable of the crime rate

boston_scaled$crim <- as.numeric(boston_scaled$crim)
bins <- quantile(boston_scaled$crim)
crime <- cut(boston_scaled$crim, breaks = bins, include.lowest = TRUE,labels = c("low","med_low","med_high","high"))

table(crime)
## crime
##      low  med_low med_high     high 
##      127      126      126      127
# Drop the crim variable and add crime variable

boston_scaled <- dplyr::select(boston_scaled, -crim)
boston_scaled <- data.frame(boston_scaled, crime)

# Divide the dataset 

n <- nrow(boston_scaled)
ind <- sample(n,  size = n * 0.8)
train <- boston_scaled[ind,]
test <- boston_scaled[-ind,]

Fit the linear discriminant analysis

# Creating the model
lda.fit <- lda(crime ~ ., data = train)
lda.fit
## Call:
## lda(crime ~ ., data = train)
## 
## Prior probabilities of groups:
##       low   med_low  med_high      high 
## 0.2475248 0.2475248 0.2524752 0.2524752 
## 
## Group means:
##                  zn      indus        chas        nox          rm        age
## low       0.9439986 -0.8561482 -0.07547406 -0.8713159  0.46156803 -0.8442935
## med_low  -0.1489396 -0.2074352 -0.03610305 -0.5170630 -0.15257867 -0.2321906
## med_high -0.3930786  0.1881207  0.22945822  0.4397051  0.03174814  0.4261169
## high     -0.4872402  1.0171096 -0.04073494  1.0630805 -0.35195732  0.8178021
##                 dis        rad        tax     ptratio       black       lstat
## low       0.8225070 -0.6855667 -0.7644438 -0.42381371  0.38136174 -0.75853754
## med_low   0.2510793 -0.5511961 -0.4468876 -0.03073223  0.31423748 -0.07019450
## med_high -0.3637260 -0.4053858 -0.2896429 -0.24845269  0.04814488  0.03604884
## high     -0.8439063  1.6382099  1.5141140  0.78087177 -0.86588545  0.95020413
##                 medv
## low       0.54867202
## med_low  -0.03216299
## med_high  0.09471625
## high     -0.73589473
## 
## Coefficients of linear discriminants:
##                  LD1          LD2         LD3
## zn       0.067991911  0.788282707 -0.87403685
## indus    0.007873984 -0.080004355  0.24316158
## chas    -0.068535208 -0.046514046  0.05729580
## nox      0.390982609 -0.774084361 -1.43956310
## rm      -0.090522299  0.004810719 -0.07950965
## age      0.250902992 -0.365549046 -0.13100452
## dis     -0.028386691 -0.365514208  0.09467384
## rad      3.225231420  1.016277534 -0.24607817
## tax     -0.047738699 -0.216902384  0.77129621
## ptratio  0.147369406 -0.006510985 -0.32895033
## black   -0.130430927  0.031804843  0.11693427
## lstat    0.222480353 -0.140012109  0.45392594
## medv     0.185418675 -0.381530212 -0.25431491
## 
## Proportion of trace:
##    LD1    LD2    LD3 
## 0.9500 0.0364 0.0136
# Visualization of the model
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
  heads <- coef(x)
  arrows(x0 = 0, y0 = 0, 
         x1 = myscale * heads[,choices[1]], 
         y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
  text(myscale * heads[,choices], labels = row.names(heads), 
       cex = tex, col=color, pos=3)
}

classes <- as.numeric(train$crime)
plot(lda.fit, dimen = 2, col = classes, pch = classes)
lda.arrows(lda.fit, myscale = 2)

The Linear Discriminant Analysis was able to separate the high crime classes well from the other classes (low, med_low, med_high). The most influential line separator is the rad: index of accessibility to radial highways. On the other hand, there is a clear separation between low crime class and med_high crime class which were caused by zn (proportion of residential land zoned for lots over 25,000 sq.ft.) and the nox (nitrogen oxides concentration (parts per 10 million)). This may be due to the differences in rural and urban setting.

The first discriminant function separates 95.25% of the population, while the second discriminant function separates 3.75% of the population. The third discriminant function separates only 1% of the population.

Prediction with the LDA Model

# Save the correct classes and remove the criome variables from the test data
correct_classes <- test$crime

test <- dplyr::select(test, -crime)
#predict with the created model
lda.pred <- predict(lda.fit, newdata = test)

#perform cross tabulation
table(correct = correct_classes, predicted = lda.pred$class)
##           predicted
## correct    low med_low med_high high
##   low       19       8        0    0
##   med_low    9      15        2    0
##   med_high   0       7       16    1
##   high       0       0        0   25

The model predicts the high crime class well. The model didn’t predict the low crime class well. Out of 102 observations, 71% of them were correctly predicted. Thus, the model can be used for further prediction purposes.

Clustering

# Reload and scale data set
data(Boston)
boston_scaled <- scale(Boston)

# Create euclidean distance matrix 
dist_eu <- dist(boston_scaled)
summary(dist_eu)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##  0.1343  3.4625  4.8241  4.9111  6.1863 14.3970
# Create Manhattan distance matrix 
dist_man <- dist(boston_scaled, method = "manhattan")
summary(dist_man)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##  0.2662  8.4832 12.6090 13.5488 17.7568 48.8618

The distances of each method gives us a different result.

# k-means clustering
km <- kmeans(boston_scaled, centers = 3)

# plot the Boston dataset with clusters
pairs(boston_scaled, col = km$cluster)

# Optimal number of clusters
set.seed(123)
k_max <- 10
twcss <- sapply(1:k_max, function(k){kmeans(boston_scaled, k)$tot.withinss})

# Visualization
library(ggplot2)
qplot(x = 1:k_max, y = twcss, geom = 'line')
## Warning: `qplot()` was deprecated in ggplot2 3.4.0.

According to the above graph, two clusters would be the optimal number of clusters in this case.

# k-means clustering for 2 clusters
km <-kmeans(boston_scaled, centers = 2)

# plot the normalized Boston dataset with clusters
pairs(boston_scaled, col = km$cluster)

km <- kmeans(boston_scaled, centers = 2)
pairs(boston_scaled[,c(1,2,3,4,5,6,7)], col = km$cluster)

km <- kmeans(boston_scaled, centers = 2)
pairs(boston_scaled[,c(8,9,10,11,12,13,14)], col = km$cluster)

The pairs plot shows a clear separation of two populations in some variables. One cluster is associated with low crimes, low proportion of non-retail business acres per town, low nitrogen oxides concentration, lower age, and high median value of owner-occupied homes.

Bonus

# k-means clustering
km2 <- kmeans(boston_scaled, centers = 3)

# plot the Boston dataset with clusters
pairs(boston_scaled, col = km2$cluster)

# linear discriminant analysis
boston_scaled <- data.frame(scale(Boston))
lda.fit2 <- lda(km2$cluster ~ ., data = boston_scaled)

# print the lda.fit object
lda.fit2
## Call:
## lda(km2$cluster ~ ., data = boston_scaled)
## 
## Prior probabilities of groups:
##         1         2         3 
## 0.4664032 0.3241107 0.2094862 
## 
## Group means:
##         crim         zn     indus        chas        nox          rm
## 1 -0.3760908 -0.3417123 -0.296848  0.01127561 -0.3345884 -0.09228038
## 2  0.8046456 -0.4872402  1.117990  0.01575144  1.1253988 -0.46443119
## 3 -0.4075892  1.5146367 -1.068814 -0.04947434 -0.9962503  0.92400834
##           age         dis        rad        tax     ptratio      black
## 1 -0.02966623  0.05695857 -0.5803944 -0.6030198 -0.08691245  0.2863040
## 2  0.79737580 -0.85425848  1.2219249  1.2954050  0.60580719 -0.6407268
## 3 -1.16762641  1.19486951 -0.5983266 -0.6616391 -0.74378342  0.3538816
##        lstat        medv
## 1 -0.1801190  0.03577844
## 2  0.8719904 -0.68418954
## 3 -0.9480974  0.97889973
## 
## Coefficients of linear discriminants:
##                 LD1         LD2
## crim    -0.03134296  0.14880455
## zn      -0.06381527  1.22350515
## indus    0.61086696  0.10402980
## chas     0.01953161 -0.03579238
## nox      1.00230143  0.70464917
## rm      -0.16285767  0.44390394
## age     -0.07220634 -0.59785382
## dis     -0.04270475  0.45498614
## rad      0.71987743  0.02882054
## tax      0.98285440  0.70663319
## ptratio  0.22527977  0.15514668
## black   -0.01693595 -0.03181845
## lstat    0.18274033  0.50122677
## medv    -0.02892966  0.64244841
## 
## Proportion of trace:
##    LD1    LD2 
## 0.8409 0.1591
# Visualization of the model
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
  heads <- coef(x)
  arrows(x0 = 0, y0 = 0, 
         x1 = myscale * heads[,choices[1]], 
         y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
  text(myscale * heads[,choices], labels = row.names(heads), 
       cex = tex, col=color, pos=3)
}

classes <- as.numeric(km2$cluster)
plot(lda.fit2, dimen = 2, col = classes, pch = classes)
lda.arrows(lda.fit2, myscale = 3)

The clusters have separated very well. The nox (nitrogen oxides concentration), zn (proportion of residential land zoned for lots over 25,000 sq.ft.) and age (proportion of owner-occupied units built prior to 1940= seem to be the most influential line seperators.

Super Bonus

model_predictors <- dplyr::select(train, -crime)
# check the dimensions
dim(model_predictors)
## [1] 404  13
dim(lda.fit$scaling)
## [1] 13  3
# matrix multiplication
matrix_product <- as.matrix(model_predictors) %*% lda.fit$scaling
matrix_product <- as.data.frame(matrix_product)
# Visualization of the 3D Plot
library(plotly)
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:MASS':
## 
##     select
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers')
# Visualization of the 3D Plot (crime classes as colours)

plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers', color = train$crime)
# Visualization of the 3D Plot (k mean clusters as colours)

plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers', color = km$cluster[ind])

The first plot shows a well separated plot which has only two visible clusters. In the second plot, high crime class has a separate cluster by their own. All the other classes seem to mix with each other. Again in the third plot, there are two well separated clusters.